package com.cc.druidtrans.service;

import com.cc.druidtrans.utils.DruidUtils;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author chanchaw
 * @create 2022-11-27 9:59
 */
@Component
public class DruidTestDo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = DruidUtils.getConnection();
            String sql = "UPDATE bank SET balance=? WHERE id=?";
            ps = conn.prepareStatement(sql);
            // 关闭自动提交，即开启事务
            conn.setAutoCommit(false);

            // 事务主体sql
            ps.setDouble(1, 3000);
            ps.setInt(2, 1001);
            ps.executeUpdate();

            //如果执行过程中发生了异常
            int a = 10 / 0;
            ps.setDouble(1, 10000);
            ps.setInt(2, 1002);
            ps.executeUpdate();
            conn.commit(); //没有发生异常，提交事务
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback(); //发生异常，回滚
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            DruidUtils.closeAll(conn, ps, null);
        }

    }
}
